package com.qclix.inv.dao;

import com.qclix.inv.Timesheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * HibernateTemplate based implementation of TimesheetDAO
 */
public class HibernateTemplateTimesheetDaoImpl extends HibernateDaoSupport implements TimesheetDAO {
    private static Logger logger = LoggerFactory.getLogger(HibernateTemplateTimesheetDaoImpl.class);

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Timesheet getTimesheet(long id) {
        return (Timesheet) getHibernateTemplate().get(Timesheet.class, id);
    }

    private static final String GET_WEEKDAY_BY_DATE = "" +
            "select ts from Timesheet ts, WeekDay wd where wd in elements(ts.days) and wd.date = ?";

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Timesheet getTimesheetStartingAtDay(Date time) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(time);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        List timesheets = getHibernateTemplate().find(GET_WEEKDAY_BY_DATE, cal.getTime());
        if (timesheets.size() == 0) {
            logger.info("no timesheet for date: " + cal.getTime());
            return null;
        }
        return (Timesheet) timesheets.get(0);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public void add(Timesheet timesheet) {
        getHibernateTemplate().saveOrUpdate(timesheet);
    }

    private static final String GET_FIRST_DAYS_OF_INVOICE = "" +
            "select min(wd.date) from WeekDay wd group by wd.timesheet";
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Set<Calendar> getFirstDaysOfTimesheets() {
        List<Date> dateList = (List<Date>) getHibernateTemplate().find(GET_FIRST_DAYS_OF_INVOICE);
        Set<Calendar> daySet = new HashSet<Calendar>();
        for (Date date : dateList) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            daySet.add(cal);
        }
        return daySet;
    }
}
